package com.mediocre.util;

import com.mediocre.constant.Constant;
import org.springframework.util.StringUtils;


import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class TimeUtils {

    private static DateTimeFormatter dateTimeFormatter;

    public static String getTimeStr(LocalDateTime localDateTime, String pattern) {
        if (null == localDateTime)
            return null;
        if (!StringUtils.hasText(pattern))
            pattern = "yyyy-MM-ddTHH:mm:ss";
        dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
//        LocalDateTime localDateTime = LocalDateTime.now(); "YYYY-MM-ddTHH:mm:ss"
        return dateTimeFormatter.format(localDateTime);
    }

    public static String getTimeStr(LocalDateTime localDateTime) {
//        return getTimeStr(localDateTime, Constant.TIME_YMDTHMS);
        return localDateTime.toString().substring(0, 19);
    }

    public static String getTimeStr(String pattern) {
        return getTimeStr(LocalDateTime.now(), pattern);
    }

    public static String getTimeStr() {
        return getTimeStr(LocalDateTime.now());
    }

    public static Long getTimeLong(LocalDateTime localDateTime, String timeType) {
        if (Constant.TIME_SECOND.equals(timeType)) {
            return localDateTime.toEpochSecond(ZoneOffset.of("+8"));
        }else if (Constant.TIME_MILLISECOND.equals(timeType)) {
            return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        }
        return null;
    }

    public static Long getTimeLong(LocalDateTime localDateTime) {
        return getTimeLong(localDateTime, Constant.TIME_MILLISECOND);
    }

    public static Long getTimeLong(String timeType) {
        return getTimeLong(LocalDateTime.now(), timeType);
    }

    public static Long getTimeLong() {
        return getTimeLong(LocalDateTime.now());
    }

    public static LocalDateTime getLocalDateTime(String timeStr, String pattern) {
        if (!StringUtils.hasText(timeStr))
            return null;
        timeStr = timeStr.replace("T"," ");
        if (!StringUtils.hasText(pattern))
            pattern = Constant.TIME_YMDHMS;
        dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(timeStr, dateTimeFormatter);
    }

    public static LocalDateTime getLocalDateTime(String timeStr) {
        return getLocalDateTime(timeStr, Constant.TIME_YMDHMS);
    }

    public static String getLocalDateTimeStr(LocalDateTime localDateTime) {
        if (null == localDateTime)
            localDateTime = LocalDateTime.now();
        return localDateTime.toString().substring(0, 19);
    }
}
